package com.guhappy.stockutil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
/**
 * @author  bduan
 */
public class UpdateStockInfo {
    private static final Log log = LogFactory.getLog(UpdateStockInfo.class);
 
    /**
	 * 
	 */
	public UpdateStockInfo() {
		
	}

    //This is synched so we only do one request at a time
    //If yahoo doesn't return stock info we will try to return it from the map in memory
    public static void main (String [] args){
        try {
	    	List<Object> stockList = new ArrayList<Object>();
	    	//stockList = GlobalStockHome.updateAllStock(args[0]);
	    	stockList = GlobalStockHome.updateAllStock("4");
	    	Iterator<Object> it = stockList.iterator();
	    	while (it.hasNext()){
	    		Object[] row = (Object[] )it.next();
	    		String ticker = (String) row[0];
	    		String name = (String) row[1];
	    		name = name.substring(name.indexOf("\t\t")+2);
	    		GlobalStock stockInfo = null;
	            Company company = new Company();
	    		stockInfo = GlobalStockHome.findByTicker(ticker);
	        	if (stockInfo == null){
		        	stockInfo = new GlobalStock();
		            stockInfo.setCompany(company);
	        	}
	            URL yahoofin = new URL("http://finance.yahoo.com/d/quotes.csv?s=" + ticker + "&f=svl1oape7drbc1p2kjj2&e=.csv");
	            URLConnection yc = yahoofin.openConnection();
	            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
	            String inputLine;
	            while (null !=(inputLine = in.readLine()) ) {
	                String[] yahooStockInfo = inputLine.split(",");

	                stockInfo.setSticker(yahooStockInfo[0].replaceAll("\"", ""));
	                stockInfo.getCompany().setName(name);
	                stockInfo.setVolume(FormatterConverter.getLong(yahooStockInfo[1]));
	                stockInfo.setLast_price(FormatterConverter.getFloat(yahooStockInfo[2]));
	                stockInfo.setOpen_price(FormatterConverter.getFloat(yahooStockInfo[3]));
	                stockInfo.setCurr_price(FormatterConverter.getFloat(yahooStockInfo[4]));
	                stockInfo.setClose_price(FormatterConverter.getFloat(yahooStockInfo[5]));
	                stockInfo.setEps(FormatterConverter.getFloat(yahooStockInfo[6]));
	                stockInfo.setDividend(FormatterConverter.getFloat(yahooStockInfo[7]));
	                stockInfo.setPe_ratio(FormatterConverter.getFloat(yahooStockInfo[8]));
	                stockInfo.setBid(FormatterConverter.getFloat(yahooStockInfo[9]));
	                stockInfo.setChange(FormatterConverter.getFloat(yahooStockInfo[10]));
	                stockInfo.setChange_percentage(yahooStockInfo[11].replaceAll("\"", ""));
	                stockInfo.setFiftytwoweekhigh(FormatterConverter.getFloat(yahooStockInfo[12]));
	                stockInfo.setFiftytwoweeklow(FormatterConverter.getFloat(yahooStockInfo[13]));
	                StringBuffer v1= new StringBuffer(yahooStockInfo[14]);
	                for (int i = 15; i<yahooStockInfo.length ; i++){
	                	v1.append(yahooStockInfo[i]);
	                }
	                if (v1!=null && !v1.toString().trim().equals("")&& !v1.toString().trim().equals("N/A")){
	                	stockInfo.setOutstanding_shares(Long.parseLong(v1.toString().trim()));
	                }
	                stockInfo.setChartUrlSmall("http://ichart.finance.yahoo.com/t?s=" + stockInfo.getSticker());
	                stockInfo.setChartUrlLarge("http://chart.finance.yahoo.com/w?s=" + stockInfo.getSticker());
	                
	                GlobalStockHome.persist(stockInfo);
	            }
	            in.close();
	    	}
	    	
        	/*
        	GlobalStock stockInfo =  new GlobalStock();
            Company company = new Company();
            stockInfo.setCompany(company);
        URL yahoofin = new URL("http://finance.yahoo.com/d/quotes.csv?s=^GSPC&f=svl1oape7drbc1p2kjj2&e=.csv");
        URLConnection yc = yahoofin.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        while (null !=(inputLine = in.readLine()) ) {
            String[] yahooStockInfo = inputLine.split(",");

            stockInfo.setSticker(yahooStockInfo[0].replaceAll("\"", ""));
            stockInfo.getCompany().setName("^GSPC");
            stockInfo.setVolume(FormatterConverter.getLong(yahooStockInfo[1]));
            stockInfo.setLast_price(FormatterConverter.getFloat(yahooStockInfo[2]));
            stockInfo.setOpen_price(FormatterConverter.getFloat(yahooStockInfo[3]));
            stockInfo.setCurr_price(FormatterConverter.getFloat(yahooStockInfo[4]));
            stockInfo.setClose_price(FormatterConverter.getFloat(yahooStockInfo[5]));
            stockInfo.setEps(FormatterConverter.getFloat(yahooStockInfo[6]));
            stockInfo.setDividend(FormatterConverter.getFloat(yahooStockInfo[7]));
            stockInfo.setPe_ratio(FormatterConverter.getFloat(yahooStockInfo[8]));
            stockInfo.setBid(FormatterConverter.getFloat(yahooStockInfo[9]));
            stockInfo.setChange(FormatterConverter.getFloat(yahooStockInfo[10]));
            stockInfo.setChange_percentage(yahooStockInfo[11].replaceAll("\"", ""));
            stockInfo.setFiftytwoweekhigh(FormatterConverter.getFloat(yahooStockInfo[12]));
            stockInfo.setFiftytwoweeklow(FormatterConverter.getFloat(yahooStockInfo[13]));
            StringBuffer v1= new StringBuffer(yahooStockInfo[14]);
            for (int i = 15; i<yahooStockInfo.length ; i++){
            	v1.append(yahooStockInfo[i]);
            }
            if (v1!=null && !v1.toString().trim().equals("")&& !v1.toString().trim().equals("N/A")){
            	stockInfo.setOutstanding_shares(Long.parseLong(v1.toString().trim()));
            }
            stockInfo.setChartUrlSmall("http://ichart.finance.yahoo.com/t?s=" + stockInfo.getSticker());
            stockInfo.setChartUrlLarge("http://chart.finance.yahoo.com/w?s=" + stockInfo.getSticker());
            
            GlobalStockHome.persist(stockInfo);
        }
        in.close();*/
        	
        } catch (Exception ex) {
            log.error("Unable to get stockinfo for: " + ex);
        }
     }
}